package com.ansion.commonchat.contact.core;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.util.Pair;

import androidx.annotation.NonNull;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.helper.ContactsHelper;
import com.ansion.basedb.dao.helper.UserHelper;
import com.ansion.basedb.dao.model.ContactsModel;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.util.UserModelNameUtils;
import com.ansion.baseui.base.BroadcastProcessor;
import com.ansion.baseui.base.TBasePresenter;
import com.ansion.baseui.base.listener.OnPageChangeListener;
import com.ansion.baseui.base.listener.PageChangeNotifier;
import com.ansion.commonchat.contact.AppConstants;
import com.ansion.commonchat.contact.bean.ContactBaseBean;
import com.ansion.commonchat.contact.bean.ContactDividerBean;
import com.ansion.commonchat.contact.bean.ContactOtherBean;
import com.ansion.commonchat.contact.bean.ContactPermissionCardBean;
import com.ansion.commonchat.contact.bean.ContactShareBean;
import com.ansion.commonchat.contact.bean.ContactsItemSort;
import com.ansion.commonchat.contact.ui.ContactIndexHelper;
import com.ansion.commonchat.contact.ui.ContactItemOtherType;
import com.ansion.commonchat.contact.ui.ContactsFragmentNew;
import com.ansion.commonchat.contact.utils.SyncDataProgressManager;
import com.ansion.commonchat.dao.CocoDaoBroadcastUtil;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.utils.CocoLocalBroadcastUtil;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.SettingHelper;
import com.ansion.utils.permission.RealRxPermission;
import com.ansion.utils.thread.BaseSerialTask;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ContactsPresenter extends TBasePresenter<ContactsFragmentNew> {

    private ArrayList<Long> uidList = new ArrayList<>();
    private OnPageChangeListener onPageChangeListener;
    private volatile boolean inited = false;
//    private BusReceiver busReceiver;

    @Override
    public void onRegisterListeners() {
        PageChangeNotifier.getInstance().addListener(getOnPageChangeListener());
    }

    @Override
    public void onUnregisterListeners() {
        PageChangeNotifier.getInstance().removeListener(getOnPageChangeListener());
//        if (busReceiver != null) EventBus.INSTANCE.unregister(busReceiver);
    }

    private OnPageChangeListener getOnPageChangeListener() {
        if (onPageChangeListener == null) {
            onPageChangeListener = new OnPageChangeListener(BConstant.PageChangeNotifyKey.KEY_MAIN_TAB) {
                @Override
                public void onPageSelected(int position) {
                }
            };
        }
        return onPageChangeListener;
    }
    public void goSettingPage() {
        try {
            ContactsFragmentNew fragment = getLifeCircle();
            if (fragment != null) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromParts("package", fragment.getContext().getPackageName(), null);
                intent.setData(uri);
                fragment.startActivityForResult(intent, 43);
            }
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    public void startQueryLocalContacts() {
        queryTask.start();
    }


    private final BaseSerialTask queryTask = new BaseSerialTask() {
        @Override
        protected void executeTask() {
            VLog.d("TAG_CONTACT", "ContactsFragmentNew load start");
            Pair<List<ContactBaseBean>, List<String>> pair = loadLocalContacts();
            refreshFriendList(pair.first, pair.second);
        }
    };

    private void loadEnd() {
        VLog.stopD("TAG_CONTACT", "%s ContactsFragmentNew load end", "TAG_SERIALTASK");
        ContactsFragmentNew fragment = getLifeCircle();
        if (fragment != null && fragment.getUIProxy() != null) {
            fragment.getUIProxy().hideLoading();
        }
        CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
                SyncDataProgressManager.CONTACTFRAGMENT_LOAD_FINISH));

        //只需要init时加载一次
        if (!inited) {
            inited = true;
        }

    }

    private Pair<List<ContactBaseBean>, List<String>> loadLocalContacts() {
        List<ContactBaseBean> contactItemList = new ArrayList<>();
        CurrentUser user = LoginedUserMgr.getCurrentLoginedUser();
        if (null == user) {
            VLog.i("TAG_CONTACT", "null");
            return new Pair<>(contactItemList, Collections.emptyList());
        }

        uidList.clear();
        /**
         * 根据联系人权限，判断是否添加权限卡片入口,如果没权限则展示入口
         * ********注意********
         * ********注意********
         * ********注意********
         * 目前PermissionCar固定在第一位。
         *
         * 如果调整此PermissionCar的顺序，不固定在在第一位的话，需要
         * 同时处理ContactsAdapterUIProxy#addPermissionCardItem中的逻辑。
         * 还有 ContactsAdapterUIProxy#refreshPermission中的逻辑
         */
        if (!RealRxPermission.getInstance().isGranted(Manifest.permission.READ_CONTACTS)) {
            contactItemList.add(new ContactPermissionCardBean());
        }
        //群组
        ContactOtherBean groupChat = new ContactOtherBean(ContactItemOtherType.TypeGroupChat + "");
        contactItemList.add(groupChat);
        //公众号
        ContactOtherBean officialAccount = new ContactOtherBean(ContactItemOtherType.TypeOfficialAccount + "");
        contactItemList.add(officialAccount);
        //文件助手
        UserModel fileAssModel = UserHelper.getUserModel(ContactUtil.BOTIM_FILE_ASSISTANT_ID);
        if (fileAssModel != null) {
            ContactOtherBean contactBaseBean = new ContactOtherBean(ContactItemOtherType.TypeFileAssistant + "");
            contactBaseBean.model = fileAssModel;
            contactBaseBean.isBlock = false;
            contactItemList.add(contactBaseBean);
        }

        // contacts
        List<ContactsModel> userList = ContactsHelper.loadAll(true);

        if ((null == userList || userList.isEmpty())) {
//            ShareHelper.setHasContact(false);
            VLog.e("TAG_CONTACT", "ContactsFragmentNew loadLocalContacts ContactsModel.size is null");
        }


        List<ContactBaseBean> localContactsItemDataList = new ArrayList<>();
        List<UserModel> userCaches = new ArrayList<UserModel>();
        int babaUserCount = 0;


        if (userList != null && !userList.isEmpty()) {
            VLog.d("TAG_CONTACT", "ContactsFragmentNew loadLocalContacts ContactsModel.size " + userList.size() );
            for (ContactsModel contactsModel : userList) {
                UserModel userModel = UserHelper.getUserModel(contactsModel.getUserId());

                if (userModel == null) {
                    continue;
                }

                if (true) {//UserModelNameUtils.isContactUser(userModel)
                    localContactsItemDataList.add(new ContactBaseBean(userModel, false));
                    userCaches.add(userModel);
                } else {
                    continue;
                }

                if (UserModelNameUtils.isContactUser(userModel)) {
                    uidList.add(userModel.getUserId());
                    babaUserCount++;
                }
            }

//            SearchLocalManager.getInstance().updateContactCache(userCaches);
            Collections.sort(localContactsItemDataList, new ContactsItemSort());
//            ShareHelper.setHasContact(true);
        } else {
//            ShareHelper.setHasContact(false);
        }

        Pair<List<ContactBaseBean>, List<String>> pair = ContactIndexHelper.getIndex(localContactsItemDataList, true);
        localContactsItemDataList = pair.first;
        contactItemList.addAll(localContactsItemDataList);
        contactItemList.add(new ContactDividerBean(AppConstants.CONTACT_CONSTANTS.CONTACT_SHARE_ITEM));
        contactItemList.add(new ContactShareBean());
        VLog.d("TAG_CONTACT", "end isContactLoaded" + (ContactsHelper.isContactLoaded() && UserHelper.isMatchEnd()));

        return new Pair<>(contactItemList, pair.second);
    }

    protected void refreshFriendList(final List<ContactBaseBean> contactItemList, List<String> keys) {

        runUI(() -> {
            if (contactItemList != null && !contactItemList.isEmpty()) {
                ContactsFragmentNew fragment = getLifeCircle();
                if (fragment != null && fragment.getAdapterUIProxy() != null) {
                    fragment.getAdapterUIProxy().refreshData(contactItemList);
                    fragment.getAdapterUIProxy().checkKeys(keys);
                }
                loadEnd();
            }
        });
    }

    @Override
    protected void onRegisterBroadcast(@NonNull List<BroadcastProcessor> processors, @NonNull List<String> categories) {
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_UserTable) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_UserTableBatch) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_GroupTable) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                GroupModel m_groupModel = (GroupModel) intent.getExtras().get(
                        "group");
                if (m_groupModel != null) {
                    if (!SettingHelper.isInGroupFav(m_groupModel.getId())) {
                        //非 favgroup,无需刷新
                        return;
                    }
                }
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_ContactsTable) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_BlockModel) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_BlockModelBatch) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(CocoDaoBroadcastUtil.kDAOAction_SystemCallAndSmsModel) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(SyncDataProgressManager.SYNCDATAPROGRESS_END) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        processors.add(new BroadcastProcessor(BConstant.FriendAction.ACTION_DEALGROUP_TO_FAV) {
            @Override
            public void onProcess(@NonNull Intent intent) {
                reStartQueryLocalContacts();
            }
        });
        categories.add(CocoDaoBroadcastUtil.kDAOCategory_RowReplace);
        categories.add(CocoDaoBroadcastUtil.kDAOCategory_RowRemove);
        categories.add(CocoDaoBroadcastUtil.kDAOCategory_LoadEnd);
    }

    /**
     * 重新查询数据
     */
    private void reStartQueryLocalContacts() {
        VLog.d("ansion","reStartQueryLocalContacts%s", Log.getStackTraceString(new Throwable()));
        ContactsFragmentNew fragment = getLifeCircle();
        if (fragment != null && !fragment.isFirstLoadFinish()) {
            return;
        }
        runUI(() -> {
            ContactsFragmentNew lifeCircle = getLifeCircle();
            if (lifeCircle != null && lifeCircle.getUIProxy() != null) {
                lifeCircle.getUIProxy().hideLoading();
            }
        });
        startQueryLocalContacts();
    }

    /**
     * When SessionChatFragment is destroyed, ads need to be released
     */
    @Override
    public void onDetachedView() {
        super.onDetachedView();
        VLog.d("TAG_CONTACT", "contact onDetachedView :  destroyAds ");
    }
}
